package org.jeecg.modules.demo.warehouseorder.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.allout.entity.YxAllot;
import org.jeecg.modules.demo.allout.service.IYxAllotService;
import org.jeecg.modules.demo.checkOrder.entity.checkOrder;
import org.jeecg.modules.demo.checkOrder.service.IcheckOrderService;
import org.jeecg.modules.demo.pubuyorder.service.IPuBuyOrderService;
import org.jeecg.modules.demo.pusettlement.service.IPuSettlementService;
import org.jeecg.modules.demo.soOrderDetail.entity.SoOrderDetail;
import org.jeecg.modules.demo.soOrderDetail.service.ISoOrderDetailService;
import org.jeecg.modules.demo.utils.CreateCodeUtil;
import org.jeecg.modules.demo.utils.generateOddUtil;
import org.jeecg.modules.demo.warehouseorder.entity.WarehouseOrder;
import org.jeecg.modules.demo.warehouseorder.service.IWarehouseOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

 /**
 * @Description: warehouse_order
 * @Author: jeecg-boot
 * @Date:   2021-12-02
 * @Version: V1.0
 */
@Api(tags="warehouse_order")
@RestController
@RequestMapping("/warehouseorder/warehouseOrder")
@Slf4j
public class WarehouseOrderController extends JeecgController<WarehouseOrder, IWarehouseOrderService> {
	@Autowired
	private IWarehouseOrderService warehouseOrderService;
	@Autowired
	private IPuBuyOrderService puBuyOrderService;
	@Autowired
	private IPuSettlementService puSettlementService;
	@Autowired
	private IcheckOrderService icheckOrderService;
	@Autowired
	private IYxAllotService yxAllotService;
	@Autowired
	private ISoOrderDetailService soOrderDetailService;
	 @Autowired
	 private ISysBaseAPI sysBaseAPI;

	/**
	 * 分页列表查询
	 *
	 * @param warehouseOrder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "入库单-分页列表查询")
	@ApiOperation(value="入库单-分页列表查询", notes="入库单-分页列表查询")
	@GetMapping(value = "/list")
	@PermissionData(pageComponent="yunxiao/pubuyorderToRk/PuBuyOrderToRkList")
	public Result<?> queryPageList(WarehouseOrder warehouseOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		try{
			QueryWrapper<WarehouseOrder> queryWrapper = QueryGenerator.initQueryWrapper(warehouseOrder, req.getParameterMap());
			queryWrapper.ne("SHANCHU",1);
			queryWrapper.in("RKLB",1,4,5,6);
			Page<WarehouseOrder> page = new Page<WarehouseOrder>(pageNo, pageSize);
			IPage<WarehouseOrder> pageList = warehouseOrderService.page(page, queryWrapper);
			return Result.OK(pageList);
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(300,"网络故障！");
		}
	}
	 /**
	  * 分页列表查询
	  *
	  * @param warehouseOrder
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "其他入库单-分页列表查询")
	 @ApiOperation(value="其他入库单-分页列表查询", notes="其他入库单-分页列表查询")
	 @GetMapping(value = "/elseList")
	 @PermissionData(pageComponent="yunxiao/warehouseorderElse/WarehouseOrderElseList")
	 public Result<?> elseList(WarehouseOrder warehouseOrder,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 try{
			 QueryWrapper<WarehouseOrder> queryWrapper = QueryGenerator.initQueryWrapper(warehouseOrder, req.getParameterMap());
			 queryWrapper.ne("SHANCHU",1);
			 queryWrapper.in("RKLB",2,3,9);
			 Page<WarehouseOrder> page = new Page<WarehouseOrder>(pageNo, pageSize);
			 IPage<WarehouseOrder> pageList = warehouseOrderService.page(page, queryWrapper);
			 return Result.OK(pageList);
		 }catch (Exception e){
			 e.printStackTrace();
			 return Result.error(300,"网络故障！");
		 }
	 }

	 @PostMapping(value = "/getYkByOrder")
	 public String getYkByOrder(@RequestParam(name="str",required=true)String str){
		 Gson gson = new Gson();
		 Map map = new HashMap();
		 try{
			 Map<String,Double>  map1 = warehouseOrderService.getYkByOrder(str);
			 map.put("code",200);
			 map.put("message","查询成功！");
			 map.put("order",map1.get("PO_ORDER"));
			 map.put("ykje",map1.get("YHX_MONEY"));
			 map.put("yksl",map1.get("YHX_TOTAIL"));
			 String json = gson.toJson(map);
			 return json;
		 }catch (Exception e){
			 e.printStackTrace();
			 map.put("code",500);
			 map.put("message","系统错误！");
			 String json = gson.toJson(map);
			 return json;
		 }
	 }

	/**
	 *   添加
	 *
	 * @param warehouseOrder
	 * @return
	 */
	@AutoLog(value = "入库单-添加")
	@ApiOperation(value="入库单-添加", notes="入库单-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody WarehouseOrder warehouseOrder,HttpServletRequest req) {
		try{
			String tenantId = req.getHeader("tenant-id");
			String precode = puBuyOrderService.getTeantCodeById(Integer.parseInt(tenantId)).toUpperCase();
			String str = warehouseOrderService.getMaxCode();
			Map<String,String> map = new HashMap<>();
			map.put("maxCode",str==null?null:str);
			String name =precode+ "RK_";
			String resultCode = generateOddUtil.createCode(map,name);
			String  code = warehouseOrderService.getCode(warehouseOrder.getPoOrder());
			Map<String,String> mapCode = new HashMap<>();
			mapCode.put("maxCode",code==null?null:code);
			String prdbn = CreateCodeUtil.createCode(mapCode);
			warehouseOrder.setPrdBn(prdbn);
			warehouseOrder.setWoNo(resultCode);
			if(warehouseOrderService.addRkOrder(warehouseOrder)){
				return Result.OK("成功！");
			}
			return Result.error(500,"失败！");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}

	 /**
	  *  审核
	  *
	  * @param warehouseOrder
	  * @return
	  */
	 @AutoLog(value = "入库单-审核")
	 @ApiOperation(value="入库单-审核", notes="入库单-审核")
	 @PostMapping(value = "/checkWarehouseOrder")
	 public Result<?> checkWarehouseOrder(@RequestBody WarehouseOrder warehouseOrder) {
	 	try {
			// 获取登录用户信息
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			if(!sysUser.getId().equals(warehouseOrder.getSaleman())){
				return Result.error(500,"您不是当前单据的指定审核人！");
			}
			List<checkOrder> orders = icheckOrderService.getByWhNum(warehouseOrder.getWhNum());
			if(!orders.isEmpty()){
				return Result.error(300,"仓库正在盘点，无法审核！");
			}
	 		if (warehouseOrder.getShenhe()==1){
	 			return Result.error(300,"已审核，无需重复审核！");
			}

	 		if(warehouseOrder.getDbNo()!=null){
				YxAllot yxAllot = yxAllotService.getByDbNo(warehouseOrder.getDbNo());
				yxAllot.setEndTime(new Date());
				yxAllotService.updateById(yxAllot);
			}
	 		if(warehouseOrderService.checkWarehouseOrder(warehouseOrder)){
				return Result.OK("审核成功!");
			}

			return  Result.error(500,"审核失败!");
		}catch (Exception e){
	 		e.printStackTrace();
	 		return  Result.error(500,"系统错误!");
		}

	 }
	 /**
	  *  弃审
	  *
	  * @param warehouseOrder
	  * @return
	  */
	 @AutoLog(value = "入库单-弃审")
	 @ApiOperation(value="入库单-弃审", notes="入库单-弃审")
	 @PostMapping(value = "/waiveChecKWarehouseOrder")
	 public Result<?> waiveChecKWarehouseOrder(@RequestBody WarehouseOrder warehouseOrder) {
		 try {
			 // 获取登录用户信息
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 if(!sysUser.getId().equals(warehouseOrder.getSaleman())){
				 return Result.error(500,"您不是当前单据的指定审核人！");
			 }
			 if (warehouseOrder.getShenhe()==0){
				 return Result.error(300,"请先审核入库单！");
			 }

			 List<String> ids = puSettlementService.selectByRkOrder(warehouseOrder.getWoNo());
			 if(!ids.isEmpty()){
			 	return Result.error(300,"已生成结算单，无法弃审！");
			 }
			 List<SoOrderDetail> soOrderDetails =soOrderDetailService.getByWoNo(warehouseOrder.getWoNo());
			 if(!soOrderDetails.isEmpty()){
				 return Result.error(300,"该入库单已生成过销售出库单，无法弃审！");
			 }
			 if(warehouseOrder.getDbNo()!=null){
				 YxAllot yxAllot = yxAllotService.getByDbNo(warehouseOrder.getDbNo());
				 yxAllotService.updateEndTimeById(yxAllot.getDbNo());
			 }
			 if(warehouseOrderService.waiveChecKWarehouseOrder(warehouseOrder)){
				 return Result.OK("弃审成功!");
			 }

			 return  Result.error(500,"弃审失败!");
		 }catch (Exception e){
			 e.printStackTrace();
			 return  Result.error(500,"系统错误!");
		 }

	 }

	/**
	 *  编辑
	 *
	 * @param warehouseOrder
	 * @return
	 */
	@AutoLog(value = "入库单-编辑")
	@ApiOperation(value="入库单-编辑", notes="入库单-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody WarehouseOrder warehouseOrder) {
		try{
			if (warehouseOrder.getShenhe()==1){
				return Result.error("入库单已审核，无法编辑！");
			}
			if(warehouseOrder.getRklb()==9){
				warehouseOrder.setStandingstock(warehouseOrder.getDbsjsl());
				warehouseOrder.setWsdj(warehouseOrder.getFtwsdj());
				warehouseOrder.setWsje(warehouseOrder.getFtwsje());
				warehouseOrder.setHsdj(warehouseOrder.getFthsdj());
				warehouseOrder.setHsje(warehouseOrder.getFthsje());
				warehouseOrder.setTotalcost(warehouseOrder.getFtwsje());
				warehouseOrder.setFttotalcost(warehouseOrder.getFtwsje());
				warehouseOrder.setPsTax(warehouseOrder.getFtse());
				warehouseOrderService.updateById(warehouseOrder);
				return Result.OK("编辑成功!");
			}else{
				warehouseOrder.setWsdj(warehouseOrder.getFtwsdj());
				warehouseOrder.setWsje(warehouseOrder.getFtwsje());
				warehouseOrder.setHsdj(warehouseOrder.getFthsdj());
				warehouseOrder.setHsje(warehouseOrder.getFthsje());
				warehouseOrder.setTotalcost(warehouseOrder.getFtwsje());
				warehouseOrder.setFttotalcost(warehouseOrder.getFtwsje());
				warehouseOrder.setPsTax(warehouseOrder.getFtse());
				warehouseOrderService.updateById(warehouseOrder);
				return Result.OK("编辑成功!");
			}
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误!");
		}
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "入库单-通过id删除")
	@ApiOperation(value="入库单-通过id删除", notes="入库单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try{
			WarehouseOrder warehouseOrder = warehouseOrderService.getById(id);
			if (warehouseOrder.getRklb()==9){
				return Result.error(500,"入库单类型为调拨入库，无法直接删除！");
			}
			if (warehouseOrder.getShenhe()==1){
				return Result.error(500,"入库单已审核，无法删除！");
			}
			List<SoOrderDetail> soOrderDetails = soOrderDetailService.getByWoNo(warehouseOrder.getWoNo());
			if(!soOrderDetails.isEmpty()){
				return Result.error(500,"入库单已被出库单引用，无法删除！");
			}
			if(warehouseOrderService.deleteByRkId(warehouseOrder)){
				return Result.OK("删除成功!");
			}
			return  Result.error(500,"删除失败！");
		}catch (Exception e){
			e.printStackTrace();
			return  Result.error(500,"系统错误！");
		}

	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "入库单-批量删除")
	@ApiOperation(value="入库单-批量删除", notes="入库单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.warehouseOrderService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "入库单-通过id查询")
	@ApiOperation(value="入库单-通过id查询", notes="入库单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		WarehouseOrder warehouseOrder = warehouseOrderService.getById(id);
		if(warehouseOrder==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(warehouseOrder);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param warehouseOrder
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WarehouseOrder warehouseOrder) {
        return super.exportXls(request, warehouseOrder, WarehouseOrder.class, "warehouse_order");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WarehouseOrder.class);
    }





}
